package com.peng.mvvm_wan.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.peng.mvvm_wan.viewmodels.BaseModel

abstract class BaseFragment<T : BaseModel> : Fragment() {

    private var contentView: View? = null
    protected lateinit var viewModel: T

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = initViewModel()
        contentView = getBindingView() ?: inflater.inflate(getResourceId(), container, false)

        viewModel.apiLoading.observe(requireActivity(), Observer { show ->
            (activity as BaseActivity?)?.run { if (show) showLoading() else hideLoading() }
        })

        lifecycle.addObserver(viewModel)
        return contentView
    }

    abstract fun getBindingView(): View?

    abstract fun getResourceId(): Int

    abstract fun initViewModel(): T

}